package common.core.util;

import common.core.constant.Constant;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author liufubing
 * @version 1.1
 * @date 2020/10/15 0015 14:59
 */
public class FileUtil {

    public static String localPath = System.getProperty("user.dir") + "/statics";

    public static String netPath = System.getProperty("user.dir") + "/statics";

    public static String upload(MultipartFile file,String url) throws Exception {
        if(file == null) {
            throw new CustomizeRuntimeException("文件为空");
        }
        String originalFileName = file.getOriginalFilename();
        File filePath = new File(localPath + url.split("/statics")[1], originalFileName);
        // 如果文件目录不存在，创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
        }
        // 写入文件
        file.transferTo(filePath);
        return filePath.getCanonicalPath();
    }

    public static String upload(MultipartFile file) throws IOException {
        if(file == null) {
            throw new CustomizeRuntimeException("文件为空");
        }
        String originalFileName = file.getOriginalFilename();
        String[] arr = originalFileName.split("/.");
        String prefix = arr[arr.length - 1];
        String fileName = System.currentTimeMillis() + "." + prefix;
        Boolean res = Constant.IMAGE_TYPE_LIST.contains(prefix);
        String path;
        if(res) {
            path = localPath + "/image";
            netPath = netPath + "/image" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        } else {
            path = localPath + "/file";
            netPath = netPath + "/file" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        path += LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        File filePath = new File(path, fileName);
        // 如果文件目录不存在，创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
        }
        // 写入文件
        file.transferTo(filePath);
        return filePath.getCanonicalPath();
    }



    /**
     * 文件下载
     * @param response
     * @param downloadFilePath
     */
    public static void download(HttpServletResponse response, String downloadFilePath) {
        String[] arr = downloadFilePath.split("/.");
        String fileName = arr[arr.length - 2] + "." + arr[arr.length - 1];//被下载文件的名称
        File file = new File(downloadFilePath);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static boolean deleteFile(File dirFile) {
        if (!dirFile.exists()) {
            return false;
        }

        if (dirFile.isFile()) {
            return dirFile.delete();
        } else {

            for (File file : dirFile.listFiles()) {
                deleteFile(file);
            }
        }

        return dirFile.delete();
    }

}
